package test.enba.openfeign.remote;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import test.enba.openfeign.client.req.User;

/** 模拟另一个服务接口 */
@RestController
@RequestMapping("/users")
public class RemoteUserController {

  private final List<User> users = new ArrayList<>();
  private final AtomicLong counter = new AtomicLong();

  // 初始化一些测试数据
  public RemoteUserController() {
    users.add(new User(counter.incrementAndGet(), "Alice", "alice@example.com"));
    users.add(new User(counter.incrementAndGet(), "Bob", "bob@example.com"));
    users.add(new User(counter.incrementAndGet(), "恩爸编程", "enba@example.com"));
  }

  // 根据用户 ID 获取用户信息
  @GetMapping("/{id}")
  public User getUserById(@PathVariable Long id) {
    return users.stream()
        .filter(user -> user.getId().equals(id))
        .findFirst()
        .orElseThrow(() -> new RuntimeException("User not found"));
  }

  // 获取所有用户信息
  @GetMapping
  public List<User> getAllUsers() {
    return users;
  }

  // 创建新用户
  @PostMapping
  public User createUser(@RequestBody User user) {
    user.setId(counter.incrementAndGet());
    users.add(user);
    return user;
  }

  // 更新用户信息
  @PutMapping("/{id}")
  public User updateUser(@PathVariable Long id, @RequestBody User user) {
    User existingUser =
        users.stream()
            .filter(u -> u.getId().equals(id))
            .findFirst()
            .orElseThrow(() -> new RuntimeException("User not found"));
    existingUser.setName(user.getName());
    existingUser.setEmail(user.getEmail());
    return existingUser;
  }

  // 删除用户
  @DeleteMapping("/{id}")
  public void deleteUser(@PathVariable Long id) {
    users.removeIf(user -> user.getId().equals(id));
  }
}
